package com.teen9g.infoplatformserver.service.impl;

import com.teen9g.constant.ChatConstant;
import com.teen9g.dto.ChatMessageDTO;
import com.teen9g.entity.ChatMessage;
import com.teen9g.infoplatformserver.mapper.ChatMapper;
import com.teen9g.infoplatformserver.mapper.UserMapper;
import com.teen9g.infoplatformserver.service.ChatService;
import com.teen9g.vo.ChatMessageSideVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ChatServiceImpl implements ChatService {

    @Autowired
    private ChatMapper chatMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 获取用户之间的聊天历史记录
     *
     * @param userId1 用户ID1
     * @param userId2 用户ID2
     * @return 聊天历史记录列表
     */
    @Override
    public List<ChatMessage> getChatHistory(Integer userId1, Integer userId2) {
        return chatMapper.getChatHistory(userId1, userId2);
    }

    /**
     * 保存消息到数据库
     *
     * @param message 消息对象
     */
    @Override
    public ChatMessage saveMessage(ChatMessageDTO message) {
        ChatMessage chatMessage = ChatMessage.builder()
                .messageStatus(ChatConstant.CHAT_NOT_READ)
                .deletedByReceiver(false)
                .deletedBySender(false)
                .sendTime(LocalDateTime.now())
                .build();
        BeanUtils.copyProperties(message, chatMessage);
        chatMapper.insert(chatMessage);
        return chatMessage;
    }

    /**
     * 获取用户的聊天历史记录列表（左侧列表）
     *
     * @param userId 用户ID
     * @return 聊天历史记录列表
     */
    @Override
    public List<ChatMessageSideVO> getChatHistoryList(Integer userId) {
        List<ChatMessageSideVO> result = chatMapper.getChatHistoryList(userId);
        for (ChatMessageSideVO chatMessageSideVO : result) {
            //判断跟谁聊天 避免前端展示的是自己的bug
            if (chatMessageSideVO.getSenderId().equals(userId)) {
                chatMessageSideVO.setChatWithId(chatMessageSideVO.getReceiverId());
                chatMessageSideVO.setChatWith(chatMessageSideVO.getReceiverName());
            } else {
                chatMessageSideVO.setChatWithId(chatMessageSideVO.getSenderId());
                chatMessageSideVO.setChatWith(chatMessageSideVO.getSenderName());
            }
            //遍历列表，根据chatWithId获取头像 导入result
            String chatWithAvatarUrl = userMapper.getAvatarUrlByUserId(chatMessageSideVO.getChatWithId());
            chatMessageSideVO.setChatWithAvatarUrl(chatWithAvatarUrl);
        }
        return result;
    }

    /**
     * 删除用户之间的聊天记录 userId1单方面删除userId2的聊天记录
     *
     * @param userId1 用户ID1
     * @param userId2 用户ID2
     * @return 操作结果
     */
    @Override
    public String deleteChat(Integer userId1, Integer userId2) {
        int rows = chatMapper.deleteChat(userId1, userId2);
        return ChatConstant.DELETE_CHAT_SUCCESS;
    }

    /**
     * 根据搜索条件获取用户的聊天历史记录列表（左侧列表）
     * 用于左侧列表的搜索功能
     *
     * @param content 搜索内容
     * @return 聊天历史记录列表
     */
    @Override
    public List<ChatMessageSideVO> getChatHistoryListBySearch(Integer userId, String content) {
        //获取列表（此时没有头像）
        List<ChatMessageSideVO> result = chatMapper.getChatHistoryListBySearch(userId, content);
        //遍历列表，根据receiverId获取头像 导入result
        for (ChatMessageSideVO chatMessageSideVO : result) {
            Integer receiverId = chatMessageSideVO.getReceiverId();
            String avatarUrl = userMapper.getAvatarUrlByUserId(receiverId);
            chatMessageSideVO.setReceiverAvatarUrl(avatarUrl);
        }
        return result;
    }

    /**
     * 发送消息
     *
     * @param chatMessageDTO 消息DTO对象
     * @return 操作结果
     */
    @Override
    public String sendMessage(ChatMessageDTO chatMessageDTO) {
        // 检查消息是否为空
        if (chatMessageDTO.getMessageContent() == null || chatMessageDTO.getMessageContent().isEmpty()) {
            return ChatConstant.CHAT_CONSTANT_NOTNULL;
        }
        // 转换为ChatMessage对象
        ChatMessage chatMessage = ChatMessage.builder()
                .chatId(generateChatId(chatMessageDTO.getSenderId(), chatMessageDTO.getReceiverId()))
                .senderId(chatMessageDTO.getSenderId())
                .senderName(chatMessageDTO.getSenderName())
                .receiverId(chatMessageDTO.getReceiverId())
                .receiverName(chatMessageDTO.getReceiverName())
                .messageContent(chatMessageDTO.getMessageContent())
                .messageStatus(ChatConstant.CHAT_NOT_READ) // 默认消息状态为未读
                .deletedByReceiver(false) // 默认发送者可以阅读消息
                .deletedBySender(false) // 默认接收者可以阅读消息
                .sendTime(LocalDateTime.now()) // 设置发送时间
                .build();
        // 保存消息到数据库
        chatMapper.insert(chatMessage);
        return null;
    }

    /**
     * 根据chatId获取聊天历史记录
     *
     * @param chatId 聊天ID
     * @return 聊天历史记录列表
     */
    @Override
    public List<ChatMessage> getChatHistoryByChatId(String chatId) {
        return chatMapper.getChatHistoryByChatId(chatId);
    }

    /**
     * 根据chatId获取AI的聊天历史记录
     *
     * @param chatId 聊天ID
     * @return 聊天历史记录列表
     */
    @Override
    public List<ChatMessage> getAIChatHistoryByChatId(String chatId) {
        return chatMapper.getAIChatHistoryByChatId(chatId);
    }

    /**
     * 保存AI的消息到数据库
     *
     * @param aiMessage AI的消息对象
     */
    @Override
    public void saveAIMessage(ChatMessage aiMessage) {
        chatMapper.saveAIMessage(aiMessage);
    }

    /**
     * 批量更新消息状态为已读
     *
     * @param messageIds 消息ID列表
     */
    @Override
    public String updateReadStatus(List<Integer> messageIds) {
        if (messageIds == null || messageIds.isEmpty()) {
            return ChatConstant.MESSAGE_IDS_NOT_NULL;
        }
        chatMapper.updateReadStatus(messageIds);
        return ChatConstant.UPDATE_READ_STATUS_SUCCESS;
    }

    /**
     * 获取用户的聊天ID列表
     *
     * @param userId 用户ID
     * @return 聊天ID列表
     */
    @Override
    public List<String> getChatIds(Integer userId) {
        return chatMapper.getChatIds(userId);
    }

    @Override
    public ChatMessage saveMessageWithAI(ChatMessageDTO message) {
        ChatMessage chatMessage = ChatMessage.builder()
                .messageStatus(ChatConstant.CHAT_NOT_READ)
                .deletedByReceiver(false)
                .deletedBySender(false)
                .sendTime(LocalDateTime.now())
                .build();
        BeanUtils.copyProperties(message, chatMessage);
        chatMapper.insertWithAI(chatMessage);
        return chatMessage;
    }



    /**
     * 生成聊天ID
     * @param senderId 发送者ID
     * @param receiverId 接收者ID
     * @return 聊天ID
     */
    private String generateChatId(Integer senderId, Integer receiverId) {
        int min = Math.min(senderId, receiverId);
        int max = Math.max(senderId, receiverId);
        return min + "_" + max;
    }
}
